package com.filex.ads.interstitial;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout.LayoutParams;

import com.filex.ads.common.utils.Dips;
import com.filex.ads.view.CloseableLayout;

import static com.filex.ads.common.CommonKeys.AD_HEIGHT;
import static com.filex.ads.common.CommonKeys.AD_WIDTH;
import static com.filex.ads.common.CommonKeys.BROADCAST_EVENT_ID_KEY;

abstract class BaseInterstitialActivity extends Activity {

    @Nullable private CloseableLayout mCloseableLayout;
    @Nullable private Long mBroadcastIdentifier;

    public abstract View getAdView();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = getIntent();
        mBroadcastIdentifier = getBroadcastIdentifierFromIntent(intent);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

        View adView = getAdView();

        mCloseableLayout = new CloseableLayout(this);
        mCloseableLayout.setOnCloseListener(new CloseableLayout.OnCloseListener() {
            @Override
            public void onClose() {
                finish();
            }
        });

        int adWidth = intent.getIntExtra(AD_WIDTH, 320);
        int adHeight = intent.getIntExtra(AD_HEIGHT, 480);

        LayoutParams lp = new LayoutParams(Dips.dipsToIntPixels(adWidth, this), Dips.dipsToIntPixels(adHeight, this));
        lp.gravity = Gravity.CENTER;
        mCloseableLayout.addView(adView, lp);
        mCloseableLayout.setBackgroundColor(Color.parseColor("#bc000000"));

        setContentView(mCloseableLayout);
    }

    @Override
    protected void onDestroy() {
        if (mCloseableLayout != null) {
            mCloseableLayout.removeAllViews();
        }
        super.onDestroy();
    }

    @Nullable
    protected CloseableLayout getCloseableLayout() {
        return mCloseableLayout;
    }

    @Nullable
    Long getBroadcastIdentifier() {
        return mBroadcastIdentifier;
    }

    protected void showInterstitialCloseButton() {
        if (mCloseableLayout != null) {
            mCloseableLayout.setCloseVisible(true);
        }
    }

    protected void hideInterstitialCloseButton() {
        if (mCloseableLayout != null) {
            mCloseableLayout.setCloseVisible(false);
        }
    }

    protected static Long getBroadcastIdentifierFromIntent(Intent intent) {
        if (intent.hasExtra(BROADCAST_EVENT_ID_KEY)) {
            return intent.getLongExtra(BROADCAST_EVENT_ID_KEY, -1L);
        }
        return null;
    }


}
